#include "course.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "../Include/fileio_pub.h"   // 解决 log_operation 警告
#include "../Include/student_pub.h"

// 创建课程链表
CourseList* create_course_list() {
    CourseList* list = (CourseList*)malloc(sizeof(CourseList));
    if (list == NULL) {
        fprintf(stderr, "❌ 内存分配失败: 无法创建课程链表\n");
        return NULL;
    }
    list->head = NULL;
    list->count = 0;
    printf("✅ 课程链表创建成功\n");
    return list;
}

// 释放课程链表
void free_course_list(CourseList* list) {
    if (list == NULL) {
        printf("⚠️  尝试释放空的课程链表\n");
        return;
    }
    
    CourseNode* current = list->head;
    CourseNode* next;
    
    while (current != NULL) {
        next = current->next;
        free(current);
        current = next;
    }
    
    free(list);
    printf("✅ 课程链表内存已释放\n");
}

// 验证课程编号
int validate_course_id(const char* id) {
    if (id == NULL || strlen(id) == 0) {
        printf("❌ 课程编号不能为空\n");
        return 0;
    }
    
    size_t len = strlen(id);
    if (len < 3 || len > 20) {
        printf("❌ 课程编号长度应在3-20位之间\n");
        return 0;
    }
    
    // 检查格式：字母开头，后跟数字
    if (!isalpha(id[0])) {
        printf("❌ 课程编号应以字母开头\n");
        return 0;
    }
    
    for (size_t i = 1; i < len; i++) {
        if (!isalnum(id[i])) {
            printf("❌ 课程编号应只包含字母和数字\n");
            return 0;
        }
    }
    
    return 1;
}

// 验证课程名称
int validate_course_name(const char* name) {
    if (name == NULL || strlen(name) == 0) {
        printf("❌ 课程名称不能为空\n");
        return 0;
    }
    
    size_t len = strlen(name);
    if (len >= MAX_COURSE_NAME_LEN) {
        printf("❌ 课程名称过长，最大允许%d个字符\n", MAX_COURSE_NAME_LEN - 1);
        return 0;
    }
    
    return 1;
}

// 验证课程学分
int validate_course_credits(float credits) {
    if (credits <= 0 || credits > 10) {
        printf("❌ 学分应在0.5-10.0之间\n");
        return 0;
    }
    return 1;
}

// 验证课程容量
int validate_course_capacity(int max_students) {
    if (max_students <= 0 || max_students > MAX_STUDENTS) {
        printf("❌ 课程容量应在1-%d之间\n", MAX_STUDENTS);
        return 0;
    }
    return 1;
}

// 查找课程
Course* find_course(CourseList* list, const char* id) {
    if (list == NULL || id == NULL) {
        return NULL;
    }
    
    CourseNode* current = list->head;
    while (current != NULL) {
        if (strcmp(current->course.id, id) == 0) {
            return &(current->course);
        }
        current = current->next;
    }
    
    return NULL;
}

// 添加课程
int add_course(CourseList* list, const char* id, const char* name, 
               const char* type, int hours, float credits, int max_students) {
    if (list == NULL) {
        printf("❌ 课程链表未初始化\n");
        return 0;
    }
    
    // 验证输入
    if (!validate_course_id(id) || !validate_course_name(name) ||
        !validate_course_credits(credits) || !validate_course_capacity(max_students)) {
        return 0;
    }
    
    // 检查课程编号是否已存在
    if (find_course(list, id) != NULL) {
        printf("❌ 课程编号 %s 已存在\n", id);
        return 0;
    }
    
    // 验证学时
    if (hours <= 0 || hours > 200) {
        printf("❌ 授课学时应在1-200之间\n");
        return 0;
    }
    
    // 验证课程性质
    if (type == NULL || (strcmp(type, "必修") != 0 && 
                         strcmp(type, "选修") != 0 &&
                         strcmp(type, "限选") != 0)) {
        printf("❌ 课程性质应为: 必修、选修或限选\n");
        return 0;
    }
    
    // 创建新课程节点
    CourseNode* new_node = (CourseNode*)malloc(sizeof(CourseNode));
    if (new_node == NULL) {
        printf("❌ 内存分配失败: 无法创建新课程\n");
        return 0;
    }
    
    // 初始化课程信息
    strcpy(new_node->course.id, id);
    strcpy(new_node->course.name, name);
    strcpy(new_node->course.type, type);
    new_node->course.hours = hours;
    new_node->course.credits = credits;
    new_node->course.student_count = 0;
    new_node->course.max_students = max_students;
    new_node->next = NULL;
    
    // 添加到链表
    if (list->head == NULL) {
        list->head = new_node;
    } else {
        CourseNode* current = list->head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = new_node;
    }
    
    list->count++;
    printf("✅ 课程添加成功: %s - %s (%.1f学分, 容量:%d/%d)\n", 
           id, name, credits, 0, max_students);
    log_operation("ADD_COURSE", id);
    return 1;
}

// 删除课程
int delete_course(CourseList* list, const char* id) {
    if (list == NULL || list->head == NULL) {
        printf("❌ 课程链表为空\n");
        return 0;
    }
    
    if (!validate_course_id(id)) {
        return 0;
    }
    
    CourseNode* current = list->head;
    CourseNode* prev = NULL;
    
    // 查找要删除的课程
    while (current != NULL) {
        if (strcmp(current->course.id, id) == 0) {
            break;
        }
        prev = current;
        current = current->next;
    }
    
    if (current == NULL) {
        printf("❌ 未找到课程编号为 %s 的课程\n", id);
        return 0;
    }
    
    // 检查是否有学生选课
    if (current->course.student_count > 0) {
        printf("❌ 课程 %s 有 %d 名学生选课，无法删除\n", 
               id, current->course.student_count);
        return 0;
    }
    
    // 从链表中移除
    if (prev == NULL) {
        list->head = current->next;
    } else {
        prev->next = current->next;
    }
    
    printf("✅ 课程删除成功: %s - %s\n", current->course.id, current->course.name);
    log_operation("DELETE_COURSE", id);
    free(current);
    list->count--;
    
    return 1;
}

// 更新课程信息
int update_course(CourseList* list, const char* id, const char* new_name, 
                 const char* new_type, int new_hours, float new_credits, 
                 int new_max_students) {
    if (list == NULL) {
        printf("❌ 课程链表未初始化\n");
        return 0;
    }
    
    if (!validate_course_id(id) || !validate_course_name(new_name) ||
        !validate_course_credits(new_credits) || !validate_course_capacity(new_max_students)) {
        return 0;
    }
    
    Course* course = find_course(list, id);
    if (course == NULL) {
        printf("❌ 未找到课程编号为 %s 的课程\n", id);
        return 0;
    }
    
    // 验证新容量是否小于当前选课人数
    if (new_max_students < course->student_count) {
        printf("❌ 新容量(%d)不能小于当前选课人数(%d)\n", 
               new_max_students, course->student_count);
        return 0;
    }
    
    // 验证课程性质
    if (new_type == NULL || (strcmp(new_type, "必修") != 0 && 
                            strcmp(new_type, "选修") != 0 &&
                            strcmp(new_type, "限选") != 0)) {
        printf("❌ 课程性质应为: 必修、选修或限选\n");
        return 0;
    }
    
    // 验证学时
    if (new_hours <= 0 || new_hours > 200) {
        printf("❌ 授课学时应在1-200之间\n");
        return 0;
    }
    
    // 保存旧信息用于日志
    char old_name[MAX_COURSE_NAME_LEN];
    char old_type[MAX_COURSE_TYPE_LEN];
    strcpy(old_name, course->name);
    strcpy(old_type, course->type);
    
    // 更新课程信息
    strcpy(course->name, new_name);
    strcpy(course->type, new_type);
    course->hours = new_hours;
    course->credits = new_credits;
    course->max_students = new_max_students;
    
    printf("✅ 课程信息更新成功: %s\n", id);
    printf("   名称: %s → %s\n", old_name, new_name);
    printf("   性质: %s → %s\n", old_type, new_type);
    printf("   学时: %d → %d\n", course->hours, new_hours);
    printf("   学分: %.1f → %.1f\n", course->credits, new_credits);
    printf("   容量: %d → %d\n", course->max_students, new_max_students);
    
    log_operation("UPDATE_COURSE", id);
    return 1;
}

// 检查学生是否已选该课程
int is_student_enrolled(Course* course, const char* student_id) {
    for (int i = 0; i < course->student_count; i++) {
        if (strcmp(course->selected_students[i], student_id) == 0) {
            return 1;
        }
    }
    return 0;
}

// 更新课程选课人数
void update_course_enrollment(Course* course, int change) {
    course->student_count += change;
    if (course->student_count < 0) {
        course->student_count = 0;
    }
}

// 学生选课
int enroll_student_in_course(CourseList* course_list, const char* course_id, 
                            const char* student_id) {
    if (course_list == NULL) {
        printf("❌ 课程链表未初始化\n");
        return 0;
    }
    
    Course* course = find_course(course_list, course_id);
    if (course == NULL) {
        printf("❌ 未找到课程编号为 %s 的课程\n", course_id);
        return 0;
    }
    
    // 检查课程是否已满
    if (course->student_count >= course->max_students) {
        printf("❌ 课程 %s 已满 (当前: %d/%d)\n", 
               course_id, course->student_count, course->max_students);
        return 0;
    }
    
    // 检查学生是否已选该课程
    if (is_student_enrolled(course, student_id)) {
        printf("❌ 学生 %s 已选择课程 %s\n", student_id, course_id);
        return 0;
    }
    
    // 添加学生到课程
    strcpy(course->selected_students[course->student_count], student_id);
    update_course_enrollment(course, 1);
    
    printf("✅ 学生 %s 成功选课: %s - %s\n", 
           student_id, course_id, course->name);
    log_operation("ENROLL_STUDENT", course_id);
    return 1;
}

// 学生退课
int withdraw_student_from_course(CourseList* course_list, const char* course_id, 
                                const char* student_id) {
    if (course_list == NULL) {
        printf("❌ 课程链表未初始化\n");
        return 0;
    }
    
    Course* course = find_course(course_list, course_id);
    if (course == NULL) {
        printf("❌ 未找到课程编号为 %s 的课程\n", course_id);
        return 0;
    }
    
    // 查找学生在课程中的位置
    int student_index = -1;
    for (int i = 0; i < course->student_count; i++) {
        if (strcmp(course->selected_students[i], student_id) == 0) {
            student_index = i;
            break;
        }
    }
    
    if (student_index == -1) {
        printf("❌ 学生 %s 未选择课程 %s\n", student_id, course_id);
        return 0;
    }
    
    // 移除学生（将后面的学生前移）
    for (int i = student_index; i < course->student_count - 1; i++) {
        strcpy(course->selected_students[i], course->selected_students[i + 1]);
    }
    
    update_course_enrollment(course, -1);
    
    printf("✅ 学生 %s 成功退课: %s - %s\n", 
           student_id, course_id, course->name);
    log_operation("WITHDRAW_STUDENT", course_id);
    return 1;
}

// 显示课程详细信息
void display_course_details(Course* course) {
    if (course == NULL) {
        printf("❌ 课程信息为空\n");
        return;
    }
    
    printf("\n════════════════════════════════════════\n");
    printf("课程编号: %s\n", course->id);
    printf("课程名称: %s\n", course->name);
    printf("课程性质: %s\n", course->type);
    printf("授课学时: %d\n", course->hours);
    printf("学分: %.1f\n", course->credits);
    printf("选课情况: %d/%d\n", course->student_count, course->max_students);
    
    if (course->student_count > 0) {
        printf("选课学生列表:\n");
        for (int i = 0; i < course->student_count; i++) {
            printf("  %d. %s\n", i + 1, course->selected_students[i]);
        }
    } else {
        printf("尚无学生选课\n");
    }
    printf("════════════════════════════════════════\n");
}

// 显示所有课程
void display_all_courses(CourseList* list) {
    if (list == NULL || list->head == NULL) {
        printf("❌ 没有课程信息\n");
        return;
    }
    
    printf("\n════════════════════════════════════════\n");
    printf("           所有课程信息 (%d门)\n", list->count);
    printf("════════════════════════════════════════\n");
    
    CourseNode* current = list->head;
    int count = 1;
    
    while (current != NULL) {
        Course* course = &(current->course);
        printf("%d. %s - %s (%s, %.1f学分, %d/%d人)\n", 
               count++, 
               course->id, 
               course->name,
               course->type,
               course->credits,
               course->student_count,
               course->max_students);
        current = current->next;
    }
    printf("════════════════════════════════════════\n");
}

// 选课管理菜单
void course_selection_menu(StudentList* student_list, CourseList* course_list) {
    if (student_list == NULL || course_list == NULL) {
        printf("❌ 系统未正确初始化\n");
        return;
    }
    
    int choice;
    char student_id[20], course_id[20];
    
    do {
        printf("\n════════════════════════════════════════\n");
        printf("           选课管理\n");
        printf("════════════════════════════════════════\n");
        printf("1. 学生选课\n");
        printf("2. 学生退课\n");
        printf("3. 查看课程选课情况\n");
        printf("0. 返回主菜单\n");
        printf("════════════════════════════════════════\n");
        printf("请选择操作: ");
        
        scanf("%d", &choice);
        
        switch (choice) {
            case 1:
                printf("请输入学生学号: ");
                scanf("%s", student_id);
                printf("请输入课程编号: ");
                scanf("%s", course_id);
                enroll_student_in_course(course_list, course_id, student_id);
                break;
                
            case 2:
                printf("请输入学生学号: ");
                scanf("%s", student_id);
                printf("请输入课程编号: ");
                scanf("%s", course_id);
                withdraw_student_from_course(course_list, course_id, student_id);
                break;
                
            case 3:
                printf("\n[课程选课情况]\n");
                display_all_courses(course_list);
                break;
                
            case 0:
                printf("返回主菜单...\n");
                break;
                
            default:
                printf("❌ 无效的选择，请重新输入\n");
        }
        
        // 清空输入缓冲区
        while (getchar() != '\n');
        
    } while (choice != 0);
}

// 课程管理菜单
void course_management_menu(CourseList* list) {
    if (list == NULL) {
        printf("❌ 课程链表未初始化\n");
        return;
    }
    
    int choice;
    char id[20], name[MAX_COURSE_NAME_LEN], type[MAX_COURSE_TYPE_LEN];
    int hours, max_students;
    float credits;
    
    do {
        printf("\n════════════════════════════════════════\n");
        printf("           课程信息管理\n");
        printf("════════════════════════════════════════\n");
        printf("1. 添加课程\n");
        printf("2. 删除课程\n");
        printf("3. 修改课程信息\n");
        printf("4. 查找课程\n");
        printf("5. 显示所有课程\n");
        printf("6. 查看课程详情\n");
        printf("0. 返回主菜单\n");
        printf("════════════════════════════════════════\n");
        printf("请选择操作: ");
        
        scanf("%d", &choice);
        
        switch (choice) {
            case 1:
                printf("请输入课程编号: ");
                scanf("%s", id);
                printf("请输入课程名称: ");
                scanf("%s", name);
                printf("请输入课程性质(必修/选修/限选): ");
                scanf("%s", type);
                printf("请输入授课学时: ");
                scanf("%d", &hours);
                printf("请输入学分: ");
                scanf("%f", &credits);
                printf("请输入课程容量: ");
                scanf("%d", &max_students);
                add_course(list, id, name, type, hours, credits, max_students);
                break;
                
            case 2:
                printf("请输入要删除的课程编号: ");
                scanf("%s", id);
                delete_course(list, id);
                break;
                
            case 3:
                printf("请输入要修改的课程编号: ");
                scanf("%s", id);
                printf("请输入新的课程名称: ");
                scanf("%s", name);
                printf("请输入新的课程性质(必修/选修/限选): ");
                scanf("%s", type);
                printf("请输入新的授课学时: ");
                scanf("%d", &hours);
                printf("请输入新的学分: ");
                scanf("%f", &credits);
                printf("请输入新的课程容量: ");
                scanf("%d", &max_students);
                update_course(list, id, name, type, hours, credits, max_students);
                break;
                
            case 4:
                printf("请输入要查找的课程编号: ");
                scanf("%s", id);
                Course* course = find_course(list, id);
                if (course != NULL) {
                    display_course_details(course);
                } else {
                    printf("❌ 未找到课程编号为 %s 的课程\n", id);
                }
                break;
                
            case 5:
                display_all_courses(list);
                break;
                
            case 6:
                printf("请输入要查看的课程编号: ");
                scanf("%s", id);
                course = find_course(list, id);
                if (course != NULL) {
                    display_course_details(course);
                } else {
                    printf("❌ 未找到课程编号为 %s 的课程\n", id);
                }
                break;
                
            case 0:
                printf("返回主菜单...\n");
                break;
                
            default:
                printf("❌ 无效的选择，请重新输入\n");
        }
        
        // 清空输入缓冲区
        while (getchar() != '\n');
        
    } while (choice != 0);
}
